class Product < ActiveRecord::Base
  validates :title,presence:{message:': 商品没名字你还卖个毛线'}
  validates :description, presence:{message:': 描述一下能累死你么'}
  
  validates :image_url, presence:{message:': 没图，差评！'}
  
  validates :price, numericality:{greater_than_equal_to: 0.01,message:': 商品不要钱？有钱任性啊'}
  validates :title, uniqueness:{message:'already exist!',case_sensitive: true}, length: { minimum: 3 ,message:': 哥，多写几个字儿不会怀孕'}
          
  validates :image_url, format:{with: /\.(gif|jpg|png)/,
              message:': 必须是URL, 而且得是GIF, JPG 或者 PNG 类型儿的你知道不？'}

  default_scope{order:'title'}   #maybe there is a problem
  
  has_many :line_items
  has_many :orders, :through => :line_items

  before_destroy :ensure_not_referenced_by_any_line_item
  
  private

    # ensure that there are no line items referencing this product
    def ensure_not_referenced_by_any_line_item
      if line_items.empty?
        return true
      else
        errors.add(:base, 'Line Items present')
        return false
      end
    end
end
